package com.ljb.commlibrary.http;

import android.app.Application;

import com.ljb.commlibrary.okgo.HttpCallBack;
import com.ljb.commlibrary.okgo.JsonCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.Response;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * 网络请求工具类
 * Created by ljb on 2018/5/2.
 */

public class HttpUtils {
    private static HttpUtils instance;

    private HttpUtils() {
    }

    /**
     * 获取单例对象
     *
     * @return
     */
    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (instance == null) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 全局初始化,在Application中调用
     *
     * @param app
     */
    public void init(Application app) {
        //网络请求使用的是okgo,当然也可以使别的,在此处做初始化
        initOkgo(app);

    }

    /**
     * 根据url地址取消网络请求
     *
     * @param url url地址
     */
    public void stop(String url) {
        OkGo.getInstance().cancelTag(url);
    }

    /**
     * 根据url地址取消网络请求,一般情况下使用stop();方法
     * cancle();用于stop()方法不生效的情况
     *
     * @param url
     */
    public void cancle(final String url) {
        OkGo.getInstance().getDelivery().post(new Runnable() {
            @Override
            public void run() {
                OkGo.getInstance().cancelTag(url);
            }
        });
    }

    /**
     * 取消所有网络请求
     */
    public void stopAll() {
        OkGo.getInstance().cancelAll();
    }

    /**
     * 取消所有网络请求,一般情况下使用stopAll();方法
     * cancleAll();用于stopAll()方法不生效的情况
     */
    public void cancleAll() {
        OkGo.getInstance().getDelivery().post(new Runnable() {
            @Override
            public void run() {
                OkGo.getInstance().cancelAll();
            }
        });
    }

    /**
     * 网络请求中的Get方法请求数据
     *
     * @param url          url地址
     * @param httpParams   请求参数
     * @param clazz        数据模型
     * @param httpCallBack 回调
     */
    public <T> void get(String url, HttpParams httpParams, Class<T> clazz, final HttpCallBack<T> httpCallBack) {
        com.lzy.okgo.model.HttpParams params = null;
        if (httpParams != null) {
            params = new com.lzy.okgo.model.HttpParams();
            for (Map.Entry<String, String> urlParam : httpParams.getUrlParamsMap().entrySet()) {
                params.put(urlParam.getKey(), urlParam.getValue());
            }
        }
        OkGo.<T>get(url)
                .tag(url)
                .params(params)
                .execute(new JsonCallback<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (httpCallBack != null)
                            httpCallBack.onSucess(response.body());
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        if (httpCallBack != null)
                            httpCallBack.onError();
                    }
                });
    }

    /**
     * 网络请求中的Post方法
     *
     * @param url          url地址
     * @param httpParams   请求参数
     * @param clazz        数据模型
     * @param httpCallBack 回调
     */
    public <T> void post(String url, HttpParams httpParams, Class<T> clazz, final HttpCallBack<T> httpCallBack) {
        com.lzy.okgo.model.HttpParams params = null;
        if (httpParams != null) {
            params = new com.lzy.okgo.model.HttpParams();
            for (Map.Entry<String, String> urlParam : httpParams.getUrlParamsMap().entrySet()) {
                params.put(urlParam.getKey(), urlParam.getValue());
            }
        }
        OkGo.<T>post(url)
                .tag(url)
                .params(params)
                .execute(new JsonCallback<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (httpCallBack != null)
                            httpCallBack.onSucess(response.body());
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        if (httpCallBack != null)
                            httpCallBack.onError();
                    }
                });
    }

//**********************************************************************************


    //初始化Okgo
    private void initOkgo(Application app) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BASIC);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        //https相关设置
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);//信任所有证书,不安全有风险
        //配置OkGo
        OkGo.getInstance().init(app)                            //必须调用初始化
                .setOkHttpClient(builder.build())               //必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(0);                              //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
    }
}





























